<template>
  <!-- 地图 -->
  <el-dialog
    v-el-drag-dialog
    append-to-body
    title="位置查询"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <div
      v-if="visible"
      v-loading="!center"
      element-loading-text="正在加载地图"
    >
      <!-- <el-form ref="dataForm" :inline="true" class="form" :rules="rules" :model="temp">
        <el-form-item label="地址查询" prop="address">
          <el-input v-model="temp.address" placeholder="" style="width: 450px;" clearable @keyup.enter.native="search" />
        </el-form-item>
        <el-button type="primary" size="mini" @click="search">搜索</el-button>
        <el-button size="mini" @click="reset">重置</el-button>
        <span>点击地址可直接进行定位</span>
      </el-form> -->
      <div class="search">
        <label for="">筛选地点名称：</label>

        <el-autocomplete
          ref="suggestionBox"
          v-model="addressSeach"
          v-scrollLoad="getLoad"
          class="addressSeach"
          :maxlength="50"
          :debounce="300"
          popper-class="address-autocomplete"
          :fetch-suggestions="queryAddressSearch"
          placeholder="请输入联系地址"
          :trigger-on-focus="false"
          @select="handleSelect"
          @input="handleInput"
        >
          <template slot-scope="{ item }">
            <div class="name">{{ item.value }}</div>
            <span class="addr">{{ item.address }}</span>
          </template>
        </el-autocomplete>
      </div>
      <baidu-map
        class="bm-view"
        :center="center"
        :scroll-wheel-zoom="true"
        :zoom="zoom"
        inertial-dragging
        @ready="mapReady"
        @click="selectPoint"
      >
        <bm-marker
          :position="point"
          :dragging="true"
        />
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :show-address-bar="true"
          :auto-location="true"
        />
        <bm-local-search :keyword="keyword" :auto-viewport="true" @searchcomplete="search" />
      </baidu-map>
    </div>
    <div slot="footer" class="dialog-footer">
      <div class="address">
        <label for="">地点名称：</label>
        <el-input v-model="address" placeholder="请输入详细地点名称" />
      </div>
      <div class="btn">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
          保存
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import { getLocalSearch } from '@/utils/BMap'
  export default {
    name: 'location',
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector('.el-autocomplete-suggestion__list')
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition =
                listDom.offsetHeight -
                wrapDom.offsetHeight +
                37 -
                0.3 -
                wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    data() {
      return {
        visible: false,
        geolocation: null,
        temp: {
          address: ''
        },
        myGeo: null,
        center: {
          lng: null,
          lat: null
        },
        zoom: 15,
        point: {
          lng: 116.403765,
          lat: 39.914850
        },
        keyword: '',
        province: '',
        city: '',
        district: '',
        rules: {
          address: [{ required: true, message: '请输入查询地址', trigger: 'change' }]
        },
        address: '',
        resolve: undefined,
        addressSeach: '',
        addressInfo: {
          page_num: 0,
          page_size: 10
        }
      }
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          if (temp && JSON.stringify(temp) !== '{}') {
            console.log(temp)
            this.temp = temp
            this.address = this.temp.csmAddress
            if (typeof (this.center) !== 'string' && temp.longitude && temp.longitude > 0 && temp.latitude && temp.latitude > 0) {
              this.center.lng = Number(temp.longitude)
              this.center.lat = Number(temp.latitude)
            }
            this.center = { ...this.center }
            this.point = { ...this.center }
            // console.log('point',this.point)
          }
          // else {
          //   const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
          //   console.log('companyInfo', companyInfo)
          //   if (companyInfo) {
          //     this.center = companyInfo.city || '北京'
          //     this.zoom = 12
          //   }
          // }
          this.visible = true
        })
      },
      mapReady({ BMap, map }) {
        const _this = this
        // 获取自动定位方法
        this.geolocation = new BMap.Geolocation()
        // 获取逆解析方法实例
        this.myGeo = new BMap.Geocoder()
        if (this.center.lng && this.center.lat) {
          return
        }
        // 获取自动定位获取的坐标信息
        this.geolocation.getCurrentPosition(function(r) {
          console.log('对应id', r)
          if (r) {
            _this.center = {
              lng: r.point.lng,
              lat: r.point.lat
            }
            _this.point = {
              lng: r.point.lng,
              lat: r.point.lat
            }
            _this.pointToAddress(r.point)
          } else {
            const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
            console.log('companyInfo', companyInfo)
            if (companyInfo) {
              _this.center = companyInfo.city || '北京'
              _this.zoom = 12
            }
          }
          // _this.pointToAddress(r.point)
        }, { enabaleHighAccuracy: false })
      },
      // 鼠标点击地图定位点
      async selectPoint({ type, target, point, pixel, overlay }) {
        this.point = point
        this.pointToAddress(point)
      },
      getLoad() {
        console.log('i am load')
        this.addressInfo.page_num++
        this.$refs.suggestionBox.fetchSuggestions()
      },
      handleInput() {
        this.addressInfo.page_num = 0
        this.$refs.suggestionBox.fetchSuggestions()
        console.log('input')
      },
      async queryAddressSearch(queryString, cb) {
        this.getAddressSuggestionList(cb)
      },
      // 输入建议
      async getAddressSuggestionList(cb) {
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: (this.temp.provinceName || '') + (this.temp.cityName || '') + this.addressSeach,
          city: this.temp.cityName
        }
        const res = await getLocalSearch(params)
        if (res && res.results && res.results.length > 0) {
          let list = []
          list = res.results.map(item => ({
            value: item.name || '',
            location: item.location,
            address: item.address || '',
            adcode: item.adcode || '',
            province: item.province || '',
            city: item.city || '',
            area: item.area || ''
          }))
          // if (this.temp.area && this.temp.countryName) {
          //   list = list.filter(item => (item.area && item.area.includes(this.temp.countryName)) || (item.area === ''))
          // }
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionBox.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      // 地址模糊匹配
      handleSelect(item) {
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          console.log(latAndLon.lat, latAndLon.lng)
          console.log(item)
          const point = { lng: latAndLon.lng, lat: latAndLon.lat }
          this.center = point
          this.point = point
          this.province = item.province
          this.city = item.city
          this.district = item.area
          this.temp.address = item.value
        }
      },
      // 根据坐标逆解析获取地址详细描述
      pointToAddress(point) {
        const _this = this
        this.myGeo.getLocation(point, function(result) {
          if (result) {
            console.log(result, 111111111)
            _this.province = result.addressComponents.province
            _this.city = result.addressComponents.city
            _this.district = result.addressComponents.district
            let address = ''
            const ssq = _this.province + _this.city + _this.district
            if (result.surroundingPois.length > 0) {
              address = result.address + result.surroundingPois[0].title
            } else {
              address = result.address
            }
            // console.log(address.split(ssq)[1])
            // console.log(_this.point)
            _this.$set(_this, 'addressSeach', address.split(ssq)[1])
            _this.$set(_this.temp, 'address', address.split(ssq)[1])
          }
        })
      },
      search() {
        this.keyword = this.temp.address
      },
      success() {
        this.resolve({
          address: this.address,
          province: this.province,
          city: this.city,
          district: this.district,
          point: this.point,
          center: this.center
        })
        this.visible = false
      },
      reset() {
        this.temp.address = ''
        this.address = ''
        this.province = ''
        this.city = ''
        this.district = ''
        this.addressSeach = ''
        this.addressInfo = {
          page_num: 0,
          page_size: 10
        }
        // this.geolocation.getCurrentPosition((r) => {
        //   if(r) {
        //     this.keyword = r.address.province + r.address.city + r.address.district
        //     this.center = r.address.province + r.address.city + r.address.district
        //   }
        // })
      }
    }
  }
</script>

<style lang="scss" scoped>
.search {
  margin-bottom: 10px;
}

.bm-view {
  width: 100%;
  height: 500px;
}
.addressSeach {
  & /deep/ .el-input {
    width: 300px;
  }
}
/deep/ .el-dialog__footer {
  height: 70px !important;
}
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .address {
    .el-input {
      width: 400px;
    }
  }
  .btn {
    margin-top: 20px;
    text-align: right;
  }
}

/* 隐藏百度图片Logo */
/deep/ .BMap_cpyCtrl {
  display: none;
}
/deep/ .anchorBL {
  display: none;
}
</style>
<style lang="scss">

.address-autocomplete {
  li {
    padding: 7px;
    line-height: normal;
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
  }
}
</style>
